package com.baibei.ebec.home.index;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.basic.module.observer.PageDataObservable;
import com.baibei.basic.module.observer.PageObservable;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IProductApi;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.Area;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BannerInfo;
import com.baibei.model.CouponInfo;
import com.baibei.model.LastPriceInfo;
import com.baibei.model.ProductInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.RankingInfo;
import com.baibei.model.ServiceQQInfo;
import com.baibei.model.ShipmentInfo;
import com.baibei.model.SuggestNumbersInfo;
import com.baibei.model.UserInfo;
import com.baibei.model.event.UpdateUserInfoEvent;
import com.baibei.model.lastinfo;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;

import org.greenrobot.eventbus.Subscribe;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Action;
import io.reactivex.functions.Function;

/**
 * 首页实现
 * Created by ChenRui on 2017/8/4 0004 10:57.
 */
public class HomeIndexPresenterImpl extends BasicPresenterImpl<HomeIndexContract.View> implements HomeIndexContract.Presenter, IQuotationEvent {

    private IProductApi mProductApi;
    private IUserApi mUserApi;
    private PageObservable<ShipmentInfo> mPageObservable;
    private List<ShipmentInfo> mDataList;
    private ITradeApi mTradeApi;
    private List<CouponInfo> mCouponInfos;
    private List<Integer> mSuggestNumbers;
    private int mMaxCount;
    // 维护一个数据集，做排序用到
    private List<RankingInfo> mRankingInfoList;
    public HomeIndexPresenterImpl(Context context, HomeIndexContract.View view) {
        super(context, view);
        //设置指针地址
        setTag(this.toString());
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mProductApi = ApiFactory.getInstance().getProductApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
        mCouponInfos = new ArrayList<>();
        mSuggestNumbers = new ArrayList<>();
        setTag(this.toString());
        createObservable(mTradeApi.getRankingList(Area.XAG.name()).map(new Function<List<RankingInfo>, List<RankingInfo>>() {
            @Override
            public List<RankingInfo> apply(@NonNull List<RankingInfo> rankingInfos) throws Exception {
                mRankingInfoList = rankingInfos;
                return rankingInfos;
            }
        }));


        mPageObservable = new PageDataObservable<ShipmentInfo>(view) {
            @Override
            protected io.reactivex.Observable onCreateObserver(int page) {
                return createObservable(mProductApi.queryShipment(mView.getArea().name(), page));
            }

            @Override
            protected void onLoadDataComplete(List<ShipmentInfo> dataList) {
                super.onLoadDataComplete(dataList);
                mDataList = dataList;
                if (mView != null) {
                    mView.onLoadComplete();
                    mView.refreshCompleted();
                }
                // 在从缓存里面读取
                QuotationManager.getInstance().flushCache();
            }

            @Override
            protected void onNoMoreData() {
                super.onNoMoreData();
                if (mView != null) {
                    mView.onLoadComplete();
                    mView.refreshCompleted();
                }
            }


            @Override
            protected void onLoadData(int page) {
                super.onLoadData(page);
                if (mView != null) {
                    mView.refreshCompleted();
                }
            }
        };


        // 注册行情
        QuotationFilter filter = new QuotationFilter(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);
    }



    @Override
    public void loadBalanceAndCoupons() {
        createObservable(mTradeApi.getSuggestNumbers())
                .flatMap(new Function<SuggestNumbersInfo, Observable<List<CouponInfo>>>() {
                    @Override
                    public Observable<List<CouponInfo>> apply(@NonNull SuggestNumbersInfo suggestNumbersInfo) throws Exception {
                        //加载建议数量
                        mSuggestNumbers.clear();
                        String[] numberArray = suggestNumbersInfo.getNumbers().split(",");
                        for (int i = 0; i < numberArray.length; i++) {
                            mSuggestNumbers.add(i, Rx.parseInt(numberArray[i]));
                        }
                        mMaxCount = suggestNumbersInfo.getMaxNumber();
                        return createObservable(mTradeApi.getValidCouponList(mView.getProduct().getProductId()));
                    }
                })
                .flatMap(new Function<List<CouponInfo>, Observable<BalanceInfo>>() {
                    @Override
                    public Observable<BalanceInfo> apply(@NonNull List<CouponInfo> couponInfos) throws Exception {
                        //获取体验券
                        mCouponInfos.clear();
                        mCouponInfos.addAll(couponInfos);
//                        mView.onLoadCoupons(couponInfos);
                        return createObservable(mUserApi.getBalanceInfo());
                    }
                })
                .subscribe(new ApiDefaultObserver<BalanceInfo>() {
                    @Override
                    protected void onError(String s) {

                    }

                    @Override
                    protected void accept(BalanceInfo balanceInfo) {
                        //获取余额
//                        mBalanceInfo = balanceInfo;
                    }
                });
    }

    @Override
    public void loadlastprice() {
         //获取昨日关市价

        createObservable(mProductApi.getClosePrice()).subscribe(new ApiDefaultObserver<lastinfo>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                }
            }

            @Override
            protected void accept(lastinfo bannerInfos) {
                if (mView!=null){
                    mView.onLoadClosePrice(bannerInfos.getQuotations());
                }
            }
        });
    }

    @Override
    public void start() {
        super.start();

        if (mView.getArea() == Area.ALL) {
            createObservable(mProductApi.getBannerInfos()).subscribe(new ApiDefaultObserver<List<BannerInfo>>() {
                @Override
                protected void onError(String s) {
                    if (mView != null) {
                        mView.onLoadBannerFailed(s);
                    }
                }

                @Override
                protected void accept(List<BannerInfo> bannerInfos) {
                    if (mView != null) {
                        mView.onLoadBannerData(bannerInfos);
                    }
                }
            });
        }


        mPageObservable.start();
    }


    @Override
    public void destroy() {
        QuotationManager.getInstance().unregister(this);
        mPageObservable.destroy();
        super.destroy();
    }

    @Override
    @Subscribe
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        // 刷新列表
        if (Rx.isEmpty(mDataList) || mView == null) return;
        int updateCount = 0;
//        LogUtils.e("tags",mDataList);
//        LogUtils.e("tags2",quotations);
        for (ShipmentInfo shipmentInfo : mDataList) {
            List<ProductInfo> products = shipmentInfo.getProducts();
            if (Rx.isEmpty(products)) {
                continue;
            }
            for (ProductInfo product : products) {
                QuotationInfo quotationInfo = quotations.get(Rx.parseInt(product.getProductId()));
                //如果没找到行情，跳过
                if (quotationInfo == null) {
                    continue;
                }
//                LogUtils.e("tags2",quotationInfo);
                //如果价格相同，跳过
                if (quotationInfo.getMarketPrice() == product.getLastPrice()) {
                    continue;
                }
//                LogUtils.e(product.getName() + "----原价格：" + product.getLastPrice() + "  更新价格:" + quotationInfo.getMarketPrice());
                //记录更新数据，如果集合中有需要更新的，刷新界面
                updateCount++;
//                LogUtils.e("tags",quotationInfo.getMarketPrice());
                product.setLastPrice(quotationInfo.getMarketPrice());
            }
        }
        if (updateCount != 0) {
            mView.onLoadData(mDataList);
        }
    }

    @Subscribe
    public void onUpdateUserInfoEvent(UpdateUserInfoEvent event) {
        createObservable(mUserApi.getUserInfo()).subscribe(new ApiDefaultObserver<UserInfo>() {
            @Override
            protected void onError(String s) {

            }

            @Override
            protected void accept(UserInfo userInfo) {
                //保存用户对象
                LogUtils.e("tag--收到指令，并更新用户信息，得到数据:" + userInfo);
                SessionManager.getDefault().setUser(userInfo);
            }
        });
    }

    @Override
    public void getServiceQQ() {
        mView.showLoading();
        createObservable(mUserApi.queryQQUrl()).doFinally(new Action() {
            @Override
            public void run() throws Exception {
                mView.hideLoading();
            }
        }).subscribe(new ApiDefaultObserver<ServiceQQInfo>() {
            @Override
            protected void onError(String s) {
                mView.onLoadServiceQQFailed(s);
            }
            @Override
            protected void accept(ServiceQQInfo serviceQQInfo) {
                mView.onLoadServiceQQSuccess(serviceQQInfo.getQqUrl());
            }
        });
    }

    /**
     * 获取可用的体验券
     *
     * @return return
     */
    public List<CouponInfo> getValidCouponList() {
        return mCouponInfos;
    }

    @Override
    public List<Integer> getSuggestNumbers() {
        return mSuggestNumbers;
    }

    @Override
    public int getMaxDefindCount() {
        return mMaxCount;
    }
}
